package com.app.reportproblem;

import java.util.ArrayList;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.app.reportproblem.Utils.PreferenceHelper;
import com.app.reportproblem.bean.ObjProblem;
import com.app.reportproblem.httpclient.HttpClientHelper;
import com.app.reportproblem.httpclient.MyJsonHttpResponseHandler;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.graphics.Bitmap.Config;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class ViewProblemActivity extends FragmentActivity implements
		OnClickListener, LocationListener {

	TextView btnBack;
	GoogleMap googleMap;

	float mLatitude = 0;
	float mLongitude = 0;

	ArrayList<ObjProblem> objProblems = new ArrayList<ObjProblem>();
	int categoryId;
	String title;
	TextView txtCountProblem;
	
	DisplayImageOptions options = new DisplayImageOptions.Builder()
									.cacheInMemory(false)
									.cacheOnDisc(true)
									.bitmapConfig(Config.RGB_565)
									.build();
	
	ImageView icFixed;
	PreferenceHelper preferenceHelper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_problem);
		preferenceHelper = new PreferenceHelper(this);
		categoryId = getIntent().getIntExtra("categoryId", 0);
		title = getIntent().getStringExtra("title");

		btnBack = (TextView) findViewById(R.id.btn_back);
		txtCountProblem = (TextView) findViewById(R.id.txt_count_problem);
		icFixed = (ImageView) findViewById(R.id.ic_fixed);

		init();

		initMap();
	}

	void init() {
		btnBack.setOnClickListener(this);
		txtCountProblem.setText(title);
		icFixed.setOnClickListener(this);
	}

	void initMap() {
		try {
			// Loading map
			initilizeMap();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		closeActivityAnim();
	}

	public void closeActivityAnim() {
		finish();
		overridePendingTransition(R.anim.open_main, R.anim.close_next);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			closeActivityAnim();
			break;
		case R.id.ic_fixed:
			fixProblem();
			break;
		default:
			break;
		}
	}

	/**
	 * function to load map. If map is not created it will create it for you
	 * */
	private void initilizeMap() {
		if (googleMap == null) {
			// Getting reference to the SupportMapFragment
			SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
					.findFragmentById(R.id.map);

			// Getting Google Map
			googleMap = fragment.getMap();

			// check if map is created successfully or not
			if (googleMap == null) {
				Toast.makeText(getApplicationContext(),
						"Sorry! unable to create maps", Toast.LENGTH_SHORT)
						.show();
			}

			// Enabling MyLocation in Google Map
			googleMap.setMyLocationEnabled(true);

			// Getting LocationManager object from System Service
			// LOCATION_SERVICE
			LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

			// Creating a criteria object to retrieve provider
			Criteria criteria = new Criteria();

			// Getting the name of the best provider
			String provider = locationManager.getBestProvider(criteria, true);

			// Getting Current Location From GPS
			Location location = locationManager.getLastKnownLocation(provider);

			if (location != null) {
				onLocationChanged(location);
			}

			locationManager.requestLocationUpdates(provider, 20000, 0,
					new android.location.LocationListener() {

						@Override
						public void onStatusChanged(String provider,
								int status, Bundle extras) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onProviderEnabled(String provider) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onProviderDisabled(String provider) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onLocationChanged(Location location) {
							// TODO Auto-generated method stub
							mLatitude = (float) location.getLatitude();
							mLongitude = (float) location.getLongitude();
							LatLng latLng = new LatLng(mLatitude, mLongitude);

							Log.i("DATA", "LAT: " + mLatitude + "LONG: "
									+ mLongitude);

							googleMap.moveCamera(CameraUpdateFactory
									.newLatLng(latLng));
							googleMap.animateCamera(CameraUpdateFactory
									.zoomTo(12));

						}
					});
			
			
			
			googleMap.setInfoWindowAdapter(new InfoWindowAdapter() {
				
				
				@Override
				public View getInfoWindow(Marker marker) {
					return null;
				}
				
				@Override
				public View getInfoContents(Marker marker) {
				// Getting view from the layout file info_window_layout
	                View v = getLayoutInflater().inflate(R.layout.maker_info, null);
	             // Getting the position from the marker
	                LatLng latLng = marker.getPosition();
	                
	                
	                // Getting reference to the TextView to set latitude
	                TextView txtNameProblem = (TextView) v.findViewById(R.id.txt_name_problem);
	                TextView tvLocation = (TextView) v.findViewById(R.id.txt_location);
	                TextView txtNameReporter = (TextView) v.findViewById(R.id.txt_name_reporter);
	                TextView txtNotes = (TextView) v.findViewById(R.id.txt_note);
	                final ImageView imgProblem = (ImageView) v.findViewById(R.id.img_problem);
	                
	                txtNameProblem.setText(title);
	                txtNotes.setText("Note: "+marker.getSnippet());
	                tvLocation.setText("Latitude: "+latLng.latitude+" "+"Longitude: "+latLng.longitude);
	                Log.i("DATA", objProblems.get(0).getImage());
	                runOnUiThread(new Thread(){

						@Override
						public void run() {
							ImageLoader.getInstance().displayImage(objProblems.get(0).getImage(),imgProblem , options);
						}
	                	
	                });
	                
	                
	                
	                
	            // Returning the view containing InfoWindow contents
	                return v;
				}
			});

			/*googleMap.addMarker(new MarkerOptions().position(
					new LatLng(mLatitude, mLongitude)).title("My Location"));*/
			
			googleMap.setOnMarkerClickListener(new OnMarkerClickListener() {
				
				@Override
				public boolean onMarkerClick(Marker marker) {
					marker.showInfoWindow();
					icFixed.setVisibility(View.VISIBLE);
					return false;
				}
			});
			googleMap.setOnMapClickListener(new OnMapClickListener() {
				
				@Override
				public void onMapClick(LatLng point) {
					icFixed.setVisibility(View.GONE);
				}
			});

		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		initilizeMap();
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		mLatitude = (float) location.getLatitude();
		mLongitude = (float) location.getLongitude();
		LatLng latLng = new LatLng(mLatitude, mLongitude);

		Log.i("DATA", "LAT: " + mLatitude + "LONG: " + mLongitude);

		googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
		googleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
		getProblem();
	}

	// getProblem
	public void getProblem() {
		Log.i("DATA", "LAY DC van de 1");
		HttpClientHelper httpClientHelper = new HttpClientHelper(
				new MyJsonHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error) {
						Log.i("DATA", "LAY DC van de 2");
						super.onFailure(error);
					}

					@Override
					public void onSuccess(JSONObject re) {
						createMarkerFromJson(re);
					}

				});

		httpClientHelper.getProblem(categoryId, mLongitude, mLatitude);
	}
	
	void createMarkerFromJson(JSONObject json) {
		try {
			Log.i("DATA", "LAY DC van de 3");
			int status = json.getInt("status");
			if (status == 200) {
				Log.i("DATA", "LAY DC van de 4");
				JSONArray data = json.getJSONArray("data");
				Log.i("DATA", "PROBLEM: " + data.toString());
				for (int i = 0; i < data.length(); i++) {
					JSONObject jo = data.getJSONObject(i);

					ObjProblem objProblem = new ObjProblem();

					int reportId = jo.getInt("reportId");
					double lat = jo.getDouble("lat");
					double lon = jo.getDouble("lon");
					String note = jo.getString("note");
					String address = jo.getString("address");
					String image = jo.getString("thumbnail_image")
					/*
					 * String image = jo.getString("image"); if
					 * (jo.getString("address") != null) {
					 * String address = jo.getString("address");
					 * objProblem.setAddress(address); } String
					 * created = jo.getString("created");
					 * 
					 * JSONObject user =
					 * jo.getJSONObject("user");
					 * 
					 * String userName = user.getString("user");
					 * String userMobile =
					 * user.getString("mobile"); String
					 * userEmail = user.getString("email")
					 */;

					// set vao obj
					objProblem.setReportId(reportId);
					objProblem.setLat(lat);
					objProblem.setLon(lon);
					objProblem.setAddress(address);
					objProblem.setImage(image);
					/*
					 * objProblem.setNote(note);
					 * objProblem.setImage(image);
					 * objProblem.setCreatedDate(created);
					 * objProblem.setUserName(userName);
					 * objProblem.setUserEmail(userEmail);
					 * objProblem.setUserMobile(userMobile);
					 */

					objProblems.add(objProblem);
//					addMarker();
					 Marker m = googleMap.addMarker(new MarkerOptions()
		                .title(title)
		                .snippet(objProblem.getNote())
		                .position(new LatLng(
		                        lat,lon))
		        );
				}
			} else {
				Log.i("DATA", "LAY DC van de 5");
			}

		} catch (JSONException e) {
			Log.i("DATA", "LAY DC van de 6");
			e.printStackTrace();
		}
	}

	
	void fixProblem() {
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				// TODO Auto-generated method stub
				super.onFailure(error);
			}

			@Override
			public void onSuccess(JSONObject re) {
				try {
					int status = re.getInt("status");
					switch (status) {
					case 200:
						googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
							
							@Override
							public void onInfoWindowClick(Marker marker) {
								marker.remove();
							}
						});
						Toast.makeText(ViewProblemActivity.this, "Fixed Success.", Toast.LENGTH_SHORT).show();
						break;

					case 400:
						Toast.makeText(ViewProblemActivity.this, "Fixed Failure.", Toast.LENGTH_SHORT).show();
						break;
					case 404:
						Toast.makeText(ViewProblemActivity.this, "Fixed Failure.", Toast.LENGTH_SHORT).show();
						break;
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
		});
		httpClientHelper.fixProblem(preferenceHelper.getUserId(), categoryId);
	}
	
	

}
